using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Net;
using System.Xml;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //get User Details
        XmlDocument soapEnvelopeXml = CreateSoapEnvelope(Requests.getUserDetailsRequestString());
        String soapResult=CallWebService(soapEnvelopeXml);
        parseUserXML(soapResult);

        //get All Tasks
        soapEnvelopeXml = CreateSoapEnvelope(Requests.getTasksRequestString());
        soapResult = CallWebService(soapEnvelopeXml);
        parseTasksXML(soapResult);
    }

    private String convertCordysdate(String cordysdate)
    {
        if (cordysdate.Trim().Length == 0)
            return "";
        int year = Int32.Parse(cordysdate.Substring(0, 4));
        int month = Int32.Parse(cordysdate.Substring(5, 2));
        int day = Int32.Parse(cordysdate.Substring(8, 2));
        int hour = Int32.Parse(cordysdate.Substring(11, 2));
        int minute = Int32.Parse(cordysdate.Substring(14, 2));
        int second = Int32.Parse(cordysdate.Substring(17, 2));
        DateTime datetime = new DateTime(year, month, day, hour, minute, second);
        return datetime.ToString();
    }

    private void parseTasksXML(string soapResult)
    {
        XmlDocument xmldoc = new XmlDocument();
        xmldoc.LoadXml(soapResult);
        XmlNodeList tasks = xmldoc.SelectNodes("//*[local-name()='Task']");

        generateColumn();
        int i = 0;
        String datetime=null;
        foreach(XmlNode task in tasks)
        {
            TableRow newRow = new TableRow();
            if (i % 2 == 1)
                newRow.BackColor = System.Drawing.Color.FromArgb(220, 230, 245);
            String tid=task.SelectSingleNode(".//*[local-name()='TaskId']").InnerText;
            newRow.Attributes.Add("onClick", "javascript:window.open('/CordysInbox/taskdetails.aspx?tid=" + tid + "&userdn=" + TextBox1.Text + "')");
            newRow.Attributes.Add("onmouseOver","javascript:this.style.cursor='hand'");
            Table1.Controls.Add(newRow);
            //TextBox3.Text = TextBox3.Text + " --- "+task.SelectSingleNode(".//*[local-name()='TaskId']").InnerText;
            //addcelltorow(task.SelectSingleNode(".//*[local-name()='TaskId']").InnerText, newRow);

            //addcelltorow(task.SelectSingleNode(".//*[local-name()='ProcessName']").InnerText, newRow);

            //addcelltorow(task.SelectSingleNode(".//*[local-name()='SourceType']").InnerText, newRow);

            addcelltorow(task.SelectSingleNode(".//*[local-name()='Activity']").InnerText, newRow);
            addcelltorow(task.SelectSingleNode(".//*[local-name()='ProcessName']").InnerText, newRow);
            String assignee=task.SelectSingleNode(".//*[local-name()='Assignee']").InnerText;
            int startindex=assignee.IndexOf("=")+1;
            int length = assignee.IndexOf(",")-startindex;
            addcelltorow(assignee.Substring(startindex,length), newRow);
            String cordysdate=task.SelectSingleNode(".//*[local-name()='DeliveryDate']").InnerText;
            datetime = convertCordysdate(cordysdate);
            addcelltorow(datetime.ToString(), newRow);
            cordysdate = task.SelectSingleNode(".//*[local-name()='StartDate']").InnerText;
            datetime = convertCordysdate(cordysdate);
            addcelltorow(datetime.ToString(), newRow);
            cordysdate = task.SelectSingleNode(".//*[local-name()='DueDate']").InnerText;
            datetime = convertCordysdate(cordysdate);
            addcelltorow(datetime.ToString(), newRow);

            /*cordysdate = task.SelectSingleNode(".//*[local-name()='StartedOn']").InnerText;
            datetime = convertCordysdate(cordysdate);
            addcelltorow(datetime.ToString(), newRow);

            addcelltorow(task.SelectSingleNode(".//*[local-name()='State']").InnerText, newRow);

            

            String target = task.SelectSingleNode(".//*[local-name()='Target']").InnerText;
            startindex = assignee.IndexOf("=") + 1;
            length = assignee.IndexOf(",") - startindex;
            addcelltorow(target.Substring(startindex, length), newRow);

             String sender = task.SelectSingleNode(".//*[local-name()='Sender']").InnerText;
             startindex = sender.IndexOf("=") + 1;
             length = sender.IndexOf(",") - startindex;
            addcelltorow(sender.Substring(startindex, length), newRow);*/

            i++;
        }

       
    }

    private void addheadercelltorow(String str, TableRow newRow)
    {
        TableHeaderCell newCell = new TableHeaderCell();
        newCell.Text = str;
        newCell.BorderStyle = BorderStyle.Solid;
        newCell.BorderWidth = Unit.Pixel(1);
        newCell.BorderColor = System.Drawing.Color.DodgerBlue;

        newRow.Controls.Add(newCell);
    }

    private void addcelltorow(String str,TableRow newRow)
    {
        TableCell newCell = new TableCell();
        newCell.Text = str;
        newCell.BorderStyle = BorderStyle.Solid;
        newCell.BorderWidth = Unit.Pixel(1);
        newCell.Width = Unit.Pixel(150);
        newCell.BorderColor = System.Drawing.Color.DodgerBlue;
        
        newRow.Controls.Add(newCell);
    }

    private void generateColumn()
    {
        TableHeaderRow newRow = new TableHeaderRow();
        newRow.BackColor = System.Drawing.Color.CornflowerBlue;
        newRow.ForeColor = System.Drawing.Color.White;
        Table1.Controls.Add(newRow);

        //addheadercelltorow("TaskId", newRow);

        //addheadercelltorow("ProcessName", newRow);

        //addheadercelltorow("SourceType", newRow);

        addheadercelltorow("Activity", newRow);
        addheadercelltorow("Process Name", newRow);
        addheadercelltorow("Assignee", newRow);
        addheadercelltorow("Received Date", newRow);
        addheadercelltorow("Start Date", newRow);
        addheadercelltorow("Due Date", newRow);
        

        

        

        //addheadercelltorow("StartedOn", newRow);

        //addheadercelltorow("State", newRow);

        

        //addheadercelltorow("Target", newRow);

        //addheadercelltorow("Sender", newRow);
       

    }

    public String CallWebService(XmlDocument soapEnvelopeXml)
    {
        String _url = "http://cin400332l/cordys/com.eibus.web.soap.Gateway.wcp?organization=o%3Daspinbox%2Ccn%3Dcordys%2Ccn%3Ddefinst%2Co%3Dvanenburg.com&messageOptions=0";
        String _action = "";

        
        HttpWebRequest webRequest = CreateWebRequest(_url, _action);
        InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);

        // begin async call to web request.
        IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);

        // suspend this thread until call is complete. You might want to
        // do something usefull here like update your UI.
        asyncResult.AsyncWaitHandle.WaitOne();

        // get the response from the completed web request.
        string soapResult;
        using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
        using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
        {
            soapResult = rd.ReadToEnd();
        }
        Console.Write(soapResult);
        return soapResult;
        
    }

    private void parseUserXML(String soapResult)
    {
        XmlDocument xmldoc = new XmlDocument();
        xmldoc.LoadXml(soapResult);
        XmlNode userdn = xmldoc.SelectSingleNode("//*[local-name()='UserDN']");
        TextBox1.Text = userdn.InnerText;
        XmlNode username = xmldoc.SelectSingleNode("//*[local-name()='UserDisplayName']");
        TextBox2.Text = username.InnerText;

    }

    private static HttpWebRequest CreateWebRequest(string url, string action)
    {
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
        webRequest.Credentials = CredentialCache.DefaultCredentials;
        webRequest.Accept = "*/*";
        webRequest.ContentType = "text/xml;charset=\"utf-8\"";
        webRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
        webRequest.Referer = "http://cin400332l/cordys/wcp/library/system/framework.htm";
        webRequest.Method = "POST";
        return webRequest;
    }

    private static XmlDocument CreateSoapEnvelope(String requestXML)
    {
        XmlDocument soapEnvelop = new XmlDocument();
        soapEnvelop.LoadXml(requestXML);
        //soapEnvelop.LoadXml("<SOAP:Envelope xmlns:SOAP='http://schemas.xmlsoap.org/soap/envelope/'>	<SOAP:Header xmlns:SOAP='http://schemas.xmlsoap.org/soap/envelope/'>		<header xmlns='http://schemas.cordys.com/General/1.0/'>			<Logger xmlns='http://schemas.cordys.com/General/1.0/'></Logger></header>		<i18n:international xmlns:i18n='http://www.w3.org/2005/09/ws-i18n'><locale xmlns='http://www.w3.org/2005/09/ws-i18n'>en-us</locale></i18n:international></SOAP:Header><SOAP:Body>		<ExecuteProcess xmlns='http://schemas.cordys.com/bpm/execution/1.0'>			<type>definition</type>			<receiver>bpm/testbpm</receiver>			<message/>			<source>Run from Process Designer</source>		</ExecuteProcess>	</SOAP:Body></SOAP:Envelope>");
        return soapEnvelop;
    }

    private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
    {
        using (Stream stream = webRequest.GetRequestStream())
        {
            soapEnvelopeXml.Save(stream);
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        //get All Tasks
        Table1.Controls.Clear();
        XmlDocument soapEnvelopeXml = CreateSoapEnvelope(Requests.getTasksRequestString());
        String soapResult = CallWebService(soapEnvelopeXml);
        parseTasksXML(soapResult);
    }
}
